package tech.runchen.gz5055.oms.common.utils.poi;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import org.apache.poi.util.IOUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zzj
 */
@Log4j2
public class ExcelUtil {

    /**
     * 导入导出数据列表
     */
    private List<?> list;
    /**
     * 工作表名称
     */
    private String sheetName;
    /**
     * 实体对象
     */
    public Class clazz;
    /**
     * Excel写入器
     */
    public ExcelWriter excelWriter;

    public ExcelUtil(Class clazz) {
        this.clazz = clazz;
    }

    public void init(List<?> list, String sheetName) {
        if (list == null) {
            list = new ArrayList<>();
        }
        this.list = JSON.parseArray(JSON.toJSONString(list), clazz);
        this.sheetName = sheetName;
    }

    public void exportExcel(HttpServletResponse response, List<?> list, String sheetName) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        this.init(list, sheetName);
        exportExcel(response);
    }

    public void exportExcel(HttpServletResponse response) {
        try {
            excelWriter = EasyExcel.write(response.getOutputStream()).build();
            excelWriter.write(list, EasyExcel.writerSheet(0, sheetName).head(clazz).build());
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
        } finally {
            IOUtils.closeQuietly(excelWriter);
        }
    }

    public void importExcel(InputStream is, AnalysisEventListener listener) {
        importExcel(is, listener, 1);
    }

    public void importExcel(InputStream is, AnalysisEventListener listener, Integer headRowNumber) {
        EasyExcel.read(is, clazz, listener).sheet().headRowNumber(headRowNumber).doRead();
    }
}
